
package com.gps.gate.database;

import com.alibaba.fastjson.JSONObject;
import com.gps.common.MessageType;
import com.gps.common.cache.CacheKeys;
import com.gps.common.model.BaseModel;
import com.gps.common.model.Command;
import com.gps.gate.trans.PosTrans;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class CommandsManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommandsManager.class);

    @Resource
    private RedisTemplate<String, Integer> redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ConnectionManager connectionManager;
    @Autowired
    private PosTrans posTrans;

    public boolean sendCommand(Command command) {
        String imei = command.getImei();
        String type = command.getType();
        if (Command.TYPE_REMOVE_SESSION.equals(type)) {     //移除设备在线设备session
            this.removeActiveDevice(imei);
            return true;
        }

        ActiveDevice activeDevice = connectionManager.getActiveDevice(imei);
        if (activeDevice != null) {
            trySendOnlineCommand(activeDevice, command.getType());
        } else {     //当前命令对应的设备未在线
            LOGGER.info("Command send failed for device is not online");
        }
        return true;
    }

    static short gSerialNum = 0;
    private void trySendOnlineCommand(ActiveDevice activeDevice, String commandType) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());        //key 序列化，避免乱码
        try {
            String imei = activeDevice.getImei();
            String commandKeys = CacheKeys.getCommandKeys(commandType, imei);
            //取出redis 中的命令记录
            String cmdStr = stringRedisTemplate.opsForValue().get(commandKeys);
            if (!StringUtils.isEmpty(cmdStr)) {     //如果存在该设备的命令，则执行离线命令
                cmdStr = cmdStr.replaceAll("\\\\", "");      //格式化
                cmdStr = cmdStr.substring(1, cmdStr.length() - 1);
                Command command = JSONObject.parseObject(cmdStr, Command.class);
                short serialNum = gSerialNum++;
                command.setSerialNum(serialNum);
                //发送命令
                activeDevice.sendCommand(command);
                //存入响应需要的执行命令
                String commandForResult = JSONObject.toJSONString(command);
                stringRedisTemplate.opsForValue().set(CacheKeys.getFeedbackKeys(imei, serialNum), commandForResult,
                        15, TimeUnit.MINUTES);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("send cmd error:", e.getMessage());
        }
    }

    public void removeActiveDevice(String imei) {
        boolean result = connectionManager.removeActiveDevice(imei);
        if (result) {
            BaseModel baseModel = new BaseModel();
            baseModel.setImei(imei);
            baseModel.setServerTime(new Date());
            baseModel.setMessageType(MessageType.TYPE_OFFLINE);
            //测试环境数据推送
            posTrans.send(baseModel);
        }
    }

}
